package com.hlkj.warboot.configurer.other;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @Description: TODO 自定义RestTemplate（基于httpclient的http请求工具包）bean纳入SpringIoc容器
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/1/11 15:05
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
    public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
        // TODO RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端（基于同步、阻塞式的Http请求工具）
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 解决中文乱码的文字
        return restTemplate;
    }

    @Bean
    @ConditionalOnMissingBean({ClientHttpRequestFactory.class})
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setReadTimeout(30000);
        simpleClientHttpRequestFactory.setConnectTimeout(60000);
        return simpleClientHttpRequestFactory;
    }
}
